﻿

Ext.define('Grails.plugin.GrailsApp', {
	pageSize : 30,

    gridTitle: '列表信息',
    formTitle: '编辑信息',

	listUrl: undefined,
	deleteUrl: undefined,
	editUrl: undefined,
	saveUrl: undefined,
    modelName: undefined,

	constructor: function(config) {
		Ext.apply(this, config || {} );
        return this;
     },
	 
	getGridFields:function(){

	},
	
	getGridColumns:function(){
		
	}, 
	
	createGridStore:function(){
        var gridUrl = this.listUrl;
		return Ext.create('Ext.data.Store', {
            autoLoad: true,
			pageSize: this.pageSize,
			fields: this.getGridFields(),
//            model: this.modelName,
			proxy: {
				type: 'ajax',
                startParam: 'offset',
                limitParam: 'max',
                url: gridUrl,
				reader: {
                    type: 'json',
                    root: 'records',
					idProperty: 'id',
                    totalProperty: 'totalRecords',
                    error:function(){

                    }
				},
				simpleSortMode: true
			}
		})
	},
	getGridToolBar:function(){
		return [{
                text:'新增',
                tooltip:'新增记录',
                iconCls:'add', 
				listeners:{
					click:function(){
						var win = this.createFormPanel();
						win.show();
					},
					scope:this
				}
            }, {
                text:'修改',
                tooltip:'修改选中的一条记录',
                iconCls:'option',
				listeners:{
					click: function(){
						var selections = this.gridPanel.selModel.getSelection();
						if (selections == null || selections.length != 1){
							 Ext.MessageBox.alert('警告', '选择了多条或者0条记录!');
						}else{
                            var win = this.createFormPanel(selections[0].data.id);
                            win.show();
                        }
					},
					scope:this
				}
            }, {
                text:'删除',
                tooltip:'删除所有选中的记录',
                iconCls:'remove',
				listeners:{
					click: function(){
                        var self = this;
						var selections = this.gridPanel.selModel.getSelection();
						if (selections == null || selections.length == 0){
							 Ext.MessageBox.alert('警告', '请选择一条或者多条需要删除的记录');
						}else{
							var ids = [];
							for (var i = 0; i < selections.length; i++){
								var data = selections[i].data;
                                ids.push(data.id);
							}

                            Ext.MessageBox.confirm('确认', '确认要删除选中的记录吗?', function(){
                                Ext.Ajax.request({
                                    url:self.deleteUrl,
                                    params:{
                                        ids:ids
                                    },
                                    success: function(response){
                                        self.gridStore.load();
//                                        Ext.MessageBox.alert('提示', response.responseText);
                                    },
                                    method:"POST"
                                })
                            });

                        }
					},
					scope: this
				}
            }];
	},
	createGridPanel: function(){

		this.gridStore = this.createGridStore();
		this.gridPanel = Ext.create('Ext.grid.Panel', {
//            autoLoad:true,
			store: this.gridStore,
			selModel:  Ext.create('Ext.selection.CheckboxModel'),
   		    columnLines: true,
			columns:this.getGridColumns(),
			tbar: this.getGridToolBar(),
			bbar: {
					xtype: 'pagingtoolbar',
					store: this.gridStore,
					displayInfo: true,
					displayMsg: '显示记录 {0} - {1} of {2}',
					emptyMsg: "没有记录"
				}
		});
		return this.gridPanel;
		
	 },

	 createFormItems: function(){

	 },

    getFormFields:function(){

    },
	 
	createFormPanel:function(id, baseParams){

        var editFormUrl = this.editUrl + id;
        var saveFormUrl = this.saveUrl;
        var formId = Ext.id();
		var win = Ext.create('Ext.window.Window', {
			title: this.formTitle,
			closable: true,
			layout:'fit',
			bodyPadding: 5,
			bodyBorder: true,
			items:{
				xtype:'form',
                id: formId,
//                baseParams:baseParams,
				fieldDefaults: {
					msgTarget: 'side',
					labelWidth: 75
				},
				defaultType: 'textfield',
				defaults: {
					anchor: '100%'
				},
                reader: Ext.create('Ext.data.JsonReader', {
                    successProperty: 'success',
                    record: 'data',
//                    fields: [
//                        'id', 'username', 'email', 'mobile', 'permissions'
//                    ]
                    model:this.modelName
                }),
				items: this.createFormItems(),

				buttons: [{
					text: '保存',
                    handler:function(){
                        var form = this.up('form').getForm();
                        if (form.isValid()) {
                            form.submit({
                                url:saveFormUrl,
                                success: function(form, action) {
                                    Ext.Msg.alert('Success', action.result.msg);
                                },
                                failure: function(form, action) {
                                    Ext.Msg.alert('Failed', action.result.msg);
                                },
                                waitTitle:'提示',
                                submitEmptyText: false,
                                waitMsg: '正在保存数据,请稍候...'
                            })
                        };
                    }
				},{
					text: '取消',
                    handler:function(){
                        win.close();
                    }
				}]
			 }
		});

         win.on("show", function(){
             var formPanel = Ext.getCmp(formId);
             formPanel.getForm().load({
                 url:editFormUrl,
                 waitTitle:'提示',
                 waitMsg:'正在加载数据,请稍候...',
                 success:function () {
//                        Ext.Msg.alert('提示',  'Success')
                    },
                    failure:function () {
                        Ext.Msg.alert('提示', 'failure')
                    }
             });
         })

		return win;
	 }
})
Ext.Ajax.extraParams = {ajaxRequest:true};
Ext.Ajax.on('requestcomplete', function (conn, xhr) {
    if (xhr && xhr.getResponseHeader && xhr.getResponseHeader('auth') == "true") {
        window.location.href = '/GoIndustry/auth/login?targetUri=/admin/main.html';
    }
});
Ext.Ajax.on('requestexception', function (conn, xhr, options, e) {
    Ext.MessageBox.show({
        title:"异常",
//        msg: xhr.statusText,
        msg:xhr.responseText,
        buttons: Ext.MessageBox.OK
    });
});